<template>
  <div>
    <div class="gva-table-box">
      <el-table
        ref="multipleTable"
        :data="tableData"
        style="width: 100%"
        tooltip-effect="dark"
        row-key="ID"
        @row-click="handleRowClick"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column align="left" label="标题" prop="title" width="150" />
        <el-table-column align="left" label="需求" prop="require" width="200" />
        <el-table-column
          align="left"
          label="需求方"
          prop="publisher"
          width="150"
        />
        <el-table-column
          align="left"
          label="接单方"
          prop="candidates"
          width="200"
        />
        <el-table-column align="left" label="价格" width="150">
          <template #default="scope">
            <div>{{ scope.row.ex_price }} 元</div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="审核通过时间" width="150">
          <template #default="scope">
            <div>{{ new Date(scope.row.updated_at).toLocaleString() }}</div>
          </template>
        </el-table-column>
        <el-table-column
          align="left"
          label="其他要求"
          prop="other"
          width="180"
        />

        <!-- 操作列 -->
        <el-table-column align="right" label="操作" width="200">
          <template #default="scope">
            <!-- 使用 @click.stop 防止触发整行点击事件 -->
            <el-button type="primary" @click.stop="openRefundDialog(scope.row)">
              处理
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="gva-pagination">
        <el-pagination
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- 订单详情弹窗 -->
    <el-dialog
      v-model="dialogFormVisible"
      width="50%"
      :before-close="closeDialog"
    >
      <template #title>
        <div>订单详情</div>
      </template>
      <OrderDetail v-if="dialogFormVisible" :orderId="currentOrderId" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 退款处理弹窗 -->
    <el-dialog v-model="refundDialogVisible" title="退款处理" width="30%">
      <el-form :model="refundForm" label-width="100px">
        <el-form-item label="退款金额">
          <el-input
            v-model="refundForm.price"
            placeholder="请输入退款金额（可为空）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeRefundDialog">取消</el-button>
          <el-button type="primary" @click="confirmRefund">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { getMatchedOrderList, afterSales } from "@/api/order";
import OrderDetail from "@/components/OrderDetails.vue";

const page = ref(1);
const total = ref(0);
const pageSize = ref(10);
const tableData = ref([]);
const dialogFormVisible = ref(false);
const refundDialogVisible = ref(false);
const currentOrderId = ref(0);
const refundForm = ref({
  price: null,
});

// 获取表格数据
const getTableData = async () => {
  tableData.value = [];

  const table = await getMatchedOrderList({
    page: page.value,
    pageSize: pageSize.value,
    type: 4,
  });
  if (table.code === 0) {
    table.data.list.forEach((item) => {
      item.candidateDeatils = item.candidates;
      let candidates = [];
      if (!item.candidates || item.candidates.length === 0) {
        item.candidates = "暂无候选人";
      } else {
        item.candidates.forEach((c) => {
          candidates.push(c.nickname + "(" + c.phone + ")");
        });
        item.candidates = candidates.join(",");
      }
    });
    tableData.value = table.data.list;
    total.value = table.data.total;
    page.value = table.data.page;
    pageSize.value = table.data.pageSize;
  }
};

// 打开订单详情弹窗
const handleRowClick = (row) => {
  currentOrderId.value = row.order_id;
  dialogFormVisible.value = true;
};

const closeDialog = () => {
  dialogFormVisible.value = false;
};

// 打开退款弹窗
const openRefundDialog = (row) => {
  currentOrderId.value = row.order_id;
  refundDialogVisible.value = true;
};

// 关闭退款弹窗
const closeRefundDialog = () => {
  refundDialogVisible.value = false;
  refundForm.value.price = null; // 重置退款金额
};

// 确认退款操作
const confirmRefund = async () => {
  // 获取输入的退款金额
  const refundAmount = refundForm.value.price
    ? Number(refundForm.value.price)
    : 0;

  // 获取当前订单的原始价格（通过 currentOrderId 查找当前行数据）
  const currentOrder = tableData.value.find(
    (item) => item.order_id === currentOrderId.value
  );
  if (!currentOrder) {
    ElMessage.error("未找到对应的订单数据");
    return;
  }

  // 计算最终提交的价格
  const finalPrice = currentOrder.ex_price - refundAmount;

  // 调用 afterSales 接口，传递 order_id 和最终价格
  const res = await afterSales({
    orderId: currentOrderId.value,
    price: finalPrice,
  });

  if (res.code === 0) {
    ElMessage.success("退款操作成功！");
    closeRefundDialog();
    getTableData(); // 重新获取数据
  } else {
    ElMessage.error("退款操作失败，请重试");
  }
};

getTableData();
</script>

<style scoped>
.gva-btn-list {
  margin-bottom: 20px;
}
.el-button {
  margin-left: 10px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
